package org.cgs.web.server.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class AccessFilter implements Filter
{
	public void destroy()
	{
		// Empty method
	} // End method

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException
	{
		if (arg0 instanceof HttpServletRequest && arg1 instanceof HttpServletResponse)
		{
			HttpServletRequest req = (HttpServletRequest) arg0;
			HttpServletResponse resp = (HttpServletResponse) arg1;

			// Check if the session is invalid
			if (req.getSession().isNew() || !req.isRequestedSessionIdValid() || !Boolean.parseBoolean((String) req.getSession().getAttribute("loggedIn")))
			{
				// Send the user to the login page
				resp.sendRedirect("/cgs/instructorLogin.jsp");
				return;
			} // End if

			// User is authenticated, proceed as usual
			arg2.doFilter(arg0, arg1);
		} // End if
	} // End method

	public void init(FilterConfig arg0)
	{
		// Empty method
	} // End method
} // End class